package com.example.springboot1.limit;

/**
 * @author ckj
 * @description TODO
 * @date 2023-03-14 8:32
 */


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@RestController
public class ExcelDownloadService {

    @Autowired
    private ExcelExportService excelExportService;

    @Autowired
    private TaskExecutor taskExecutor;


    @GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<byte[]> downloadExcelRa() throws InterruptedException, ExecutionException, TimeoutException {

        CompletableFuture<byte[]> future = this.downloadExcel();

        // 等待任务完成并获取结果
        byte[] data = future.get(30, TimeUnit.SECONDS);

        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=\"example.xlsx\"")
                .body(data);

    }



    public CompletableFuture<byte[]> downloadExcel() {

        return CompletableFuture.supplyAsync(() -> {

            // 创建Excel文件并将其写入ByteArrayOutputStream
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            excelExportService.exportExcel(byteArrayOutputStream);

            return byteArrayOutputStream.toByteArray();

        }, taskExecutor);

    }
}